import fs from 'fs';
import path from 'path';
import chalk from 'chalk';

function formatNumber(value: number, length: number) {
  return value.toString().padStart(length, '0');
}

function getTimestamp() {
  const date = new Date();
  const YYYY = formatNumber(date.getUTCFullYear(), 4);
  const MM = formatNumber(date.getUTCMonth() + 1, 2);
  const DD = formatNumber(date.getUTCDate(), 2);
  const HH = formatNumber(date.getUTCHours(), 2);
  const mm = formatNumber(date.getUTCMinutes(), 2);
  const ss = formatNumber(date.getUTCSeconds(), 2);
  return `${YYYY}${MM}${DD}${HH}${mm}${ss}`;
}

export default async function (args: string[]) {
  const [table, name] = args;
  try {
    const templatePath = path.resolve(__dirname, '../../templates/migration.ts');
    const template = fs.readFileSync(templatePath).toString();
    const dir = path.resolve(process.cwd(), `sequelize/migrations${table ? '/' + table : ''}`);
    fs.mkdirSync(dir, { recursive: true });
    const filePath = path.resolve(dir, `${getTimestamp()}-${name || 'new'}.ts`);
    const text = template.replace('${table}', table);
    fs.writeFileSync(filePath, text);
    console.log(`New migration was created at ${filePath} .`);
  } catch (err: any) {
    console.error('');
    console.error(`${chalk.red('ERROR:')} ${err.message || err}`);
    console.error('');
    process.exit(1);
  }
}
